var AldeasInfantiles = angular.module("AldeasInfantiles", ['angularFileUpload']);

AldeasInfantiles.controller("Inventory", function($scope, $http, $upload, $timeout) {

  $scope.hiddenClass = "hidden"; //Used to show or hide the error message in the UI
  $scope.alertClass = ""; //Used to display a message in the UI
  $scope.errorMessage = ""; //Used to change the class of the message div in the UI
  $scope.articlesTypes = [];
  $scope.selectedtype = "";
  $scope.selectedCountry = "";
  $scope.countries = [];
  $scope.selectedDorp = "";
  $scope.dorps = [];
  $scope.selectedHouse = "";
  $scope.houses = [];
  $scope.selectedStatus = "";
  $scope.statuses = [];
  $scope.prev_img = "";
  $scope.file = undefined;
  $scope.selectedClassification = "0";
  $scope.dsResponsible = "";
  $scope.idDesponsible = "";
  $scope.resposibles = [];


  $scope.file_changed = function(element) {
    var photofile = element;
    var reader = new FileReader();
    reader.onload = function(e) {
        $scope.$apply(function() {
            $scope.prev_img = e.target.result;
        });
    };
    reader.readAsDataURL(photofile);
   };

  //Requests all countries
  $scope.requestCountries = function () {
    $http({
          method: 'POST', 
          url: currentPath + 'countries/returncountries/'
        }).
        success(function(data) {
          $scope.countries = data;
          $scope.selectedCountry = data[0].id_pais;
          $scope.requestDorps(); 
        }).
        error(function(data, status) {
          console.log(e.message);
        });
  };

  $scope.showResponsibles = function () {
    $http({
          method: 'POST', 
          url: currentPath + 'persons/returnallpersons/'
        }).
        success(function(data) {
          $scope.resposibles = data;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  $scope.getResposibleById = function (resposible){
    var id = resposible.id_persona;
    $http({
          method: 'POST', 
          url: currentPath + 'persons/returnpersonbyid/' + id
        }).
        success(function(data) {
          $scope.resposibles = data;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  }; 

  //Request all dorps
  $scope.requestDorps = function () {
    $http({
          method: 'POST', 
          url: currentPath + 'dorps/returndorpsbycountry/' + $scope.selectedCountry
        }).
        success(function(data) {
          $scope.dorps = data;
          $scope.selectedDorp = data[0].id_programa;
          $scope.requestHouses();
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Displays all houses in the UI
  $scope.requestHouses = function () {
    $http({
            method: 'POST', 
            url: currentPath + 'housing/returnhousesbydorp/' + $scope.selectedDorp
        }).
        success(function(data) {
          $scope.houses = data;
          $scope.selectedHouse = data[0].id_casa;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };


  //Displays all articles in the UI
  $scope.requestArticles = function () {
    $http({
            method: 'POST', 
            url: currentPath + 'articles/returnallarticles/'
        }).
        success(function(data) {
          $scope.articlesTypes = data;
          $scope.selectedtype = data[0].id_articulo;
          //$scope.prev_img = currentPath + 'assets/articles-images/' + data[0].imagen;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Receives the id of an user to get the information from the DB
  $scope.getArticleTypeById = function () {
    $http({
            method: 'POST', 
            url: currentPath + 'articles/returnarticlebyid/' + $scope.selectedtype
        }).
        success(function(data) {
          $scope.prev_img = currentPath + 'assets/articles-images/' + data[0].imagen;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Displays all articles in the UI
  $scope.requestArticlesStatus = function () {
    $http({
            method: 'POST', 
            url: currentPath + 'articles/returnarticlesstatus/'
        }).
        success(function(data) {
          $scope.statuses = data;
          $scope.selectedStatus = data[0].id_estado;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Loads a excel file
  $scope.loadFile = function (){
    if($scope.file===undefined){
        $scope.hiddenClass = "";
        $scope.alertClass = "alert-danger";
        $scope.errorMessage = "Debes seleccionar un archivo.";
    } else {
      $scope.saveArticle();
    }
  };

  //Saves the article in the database
  $scope.saveArticle = function () {

    $http({
        method: 'POST',
        url: currentPath + 'articles/loadarticlesfile/',
        secureuri: false,
        headers: {'Content-Type': 'multipart/form-data'},
        dataType: 'json',
        data: {
            articletype: $scope.selectedtype,
            articlecountry: $scope.selectedCountry,
            articledorp: $scope.selectedDorp,
            articlehouse: $scope.selectedHouse,
            file: $scope.file
        },
        transformRequest: function (data, headersGetter) {
            var formData = new FormData();
            angular.forEach(data, function (value, key) {
                formData.append(key, value);
            });

            var headers = headersGetter();
            delete headers['Content-Type'];

            return formData;
        }
    }).success(function(data, status, headers, config) {
      console.log(data);
      if(data.response == "success"){
        $scope.errorMessage = "Datos guardatos correctamente";
        $scope.hiddenClass = "";
        $scope.alertClass = "alert-success";
        //$scope.resetForm();
      }else if(data.response == "incomplete_form"){
        $scope.hiddenClass = "";
        $scope.alertClass = "alert-danger";
        $scope.errorMessage = "Debes escribir todos los datos del formulario.";
      }else if(data.response == "failed"){
        $scope.hiddenClass = "";
        $scope.alertClass = "alert-danger";
        $scope.errorMessage = "Algo fallo al guardar los datos, intentalo de nuevo.";
      }
    }).error(function (data, status) {
      $scope.hiddenClass = "";
      $scope.errorMessage = data;
    });
  };

  $scope.getArticleById = function(article){
    var id = articlgetArticleByIde.id_articulo;
    $http({
            method: 'POST', 
            url: currentPath + 'articles/returnarticlebyid/' + id
        }).
        success(function(data) {
          $scope.article.articleid = data[0].id_articulo;
          $scope.article.articlename = data[0].ds_articulo;
          $scope.article.description = data[0].ds_descripcion;
          $scope.selectedtype = data[0].id_tipoarticulo;
          $scope.article.features = data[0].ds_caracteristicas;
          $scope.article.comments = data[0].ds_comentarios;
          $scope.prev_img = currentPath + 'assets/articles-images/' + data[0].imagen;
          $('#modal-articles').modal('hide');
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  $scope.setDefaultSettings = function () {
    $scope.requestArticles();
    $scope.requestCountries();
    $scope.requestArticlesStatus();
  };

  $scope.setDefaultSettings();

});

AldeasInfantiles.directive('file', function () {
    return function(scope, element, attrs) {
        element.bind('change', function(event) {
          var file = event.target.files[0];
          scope.file = file ? file : undefined;
          scope.file_changed(file);
          scope.$apply();
        })
    };
});

$(document).ready(function(){
  $('.input-group.date').datepicker({
    language: "es"
  });
})